const express = require("express");
const mysql = require("mysql");
const app = express();
var swaggerUi = require("swagger-ui-express");

app.use(
  express.urlencoded({
    extended: false,
  })
);
app.use(express.json());

const pool = mysql.createPool({
  host: "localhost",
  user: "root",
  password: "root",
  port: "3306",
  database: "blog",
});

function query(sql, params, callback) {
  pool.getConnection((err, connection) => {
    connection.query(sql, params, (err, rows) => {
      callback(err, rows);
      connection.release();
    });
  });
}

const adminDocument = require("./swaggerJSON/admin.json");

// 加载admin所需要的swagger.json文件
// 访问/api/admin/swagger.html, 就会加载adminDocument对应的swagger配置
app.use(
  "/api/admin/swagger.html",
  swaggerUi.serve,
  swaggerUi.setup(adminDocument)
);

/* 获取所有用户 */
app.get("/api/getAllUser", (req, res) => {
  const sql = "select * from admin";
  query(sql, [], (err, data) => {
    res.status(200);
    res.json({
      data: data,
      msg: "获取成功",
      code: "200",
    });
  });
});

/* 根据username获取用户 */
app.get("/api/getUserByUsername/:username", (req, res) => {
  const sql = `select * from admin where username = '${req.params.username}'`;
  query(sql, [], (err, data) => {
    res.status(200);
    res.json({
      data: data,
      msg: "获取成功",
      code: "200",
    });
  });
});

/* 新增用户 */
app.post("/api/createAdmin", (req, res) => {
  const sql = `insert into admin(username, password) values('${req.body.username}', '${req.body.password}')`;
  query(sql, [], (err, data) => {
    res.status(200);
    res.json({
      msg: "新增成功",
      code: "200",
    });
  });
});

/* 删除用户 */
app.delete("/api/user/:id", (req, res) => {
  const sql = `delete from admin where id = ${req.params.id}`;
  query(sql, [], (err, data) => {
    res.status(200);
    res.json({
      msg: data.affectedRow === 1 ? "删除成功" : null,
      code: "200",
    });
  });
});

/* 修改用户 */
app.put("/api/user/:id", (req, res) => {
  const { username, id = 1, password } = req.body;
  const sql = `update admin set username = '${username}', password = '${password}' where id = ${id}`;
  query(sql, [], (err, data) => {
    console.log(data);
    res.status(200);
    res.json({
      msg: data.changedRows === 1 ? "修改成功" : null,
      code: "200",
    });
  });
});

app.listen(3000, () => {
  console.log(`Example app listening on port 3000`);
});
